package com.fz.dao;

import com.fz.entity.Book;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by webrx on 2017-09-15.
 */
@Repository
public class BookDAO {
    @Autowired
    protected SessionFactory sf;
    public List<Book> query(){
        Session session  = sf.openSession();
        return session.createQuery("from Book").list();
    }

    public void deleteById(int id){
        Session session  = sf.openSession();
        session.beginTransaction();
        //Query query = session.createQuery("delete from book id=:id");
        //query.setParameter("id",id);
        //query.executeUpdate();
        session.delete(session.load(Book.class,id));
        session.getTransaction().commit();
        session.close();
    }

    public void save(String name){
        Session session  = sf.openSession();
        session.beginTransaction();
        Book b = new Book();
        b.setName(name);
        session.save(b);
        session.getTransaction().commit();
        session.close();
    }
}
